package aes.general;

import java.awt.CardLayout;
import java.awt.FileDialog;
import java.awt.Frame;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.rtf.RtfWriter2;

import aes.gui.StudentFrame;
import aes.gui.StudentGetManualExamCopy;
import aes.gui.StudentMakeExam;
import aes.gui.StudentMakeExamAutomated;
import aes.gui.StudentMakeExamManualSubmitPane;


/**
 * The Class StudentControl. Contains Methods relevant to different functionality relevant to Student.
 */
public class StudentControl {

	/** The Grades Vector. */
	public static Vector<Vector<String>> gradesvector = null;
	
	/** The Finished exam info. */
	public static Vector<Vector<String>> FinishedExamInfo = null;

	/**
	 * Check activation code .Request to Server.
	 *
	 * @param code the code
	 */
	public static void CheckActivationCodeID(String code) {

		System.out.println("Called Check Activation Code ID");
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			System.out.println("202 cannot openconnection");
			e.printStackTrace();
		}
		Msg request1 = new Msg(code, "202");
		GuiControlBeta.getClient().handleMessageFromClientUI(request1);
	}

	/**
	 * Called by client as a result of CheckActivationCodeID call. Sets appropriate flag indication if Activation code correct.
	 *  Generally not for User to Call.
	 * 
	 * @param msg the reply from server
	 */
	public static void GetExam(Object msg) {
		if (((Msg) msg).getMsg() == "error")
			StudentMakeExam.ActivationCodeFlag = false;

		if (((Msg) msg).getMsg().toString().equals("Ok"))
			StudentMakeExam.ActivationCodeFlag = true;
	}

	/**
	 * Send "Manual" exam file to Server.
	 *
	 * @param file1 the exam file
	 */
	public static void SendManualExamFile(FileSend file1) {

		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {

			e.printStackTrace();
		}

		Msg request1 = new Msg(file1, "204");
		GuiControlBeta.getClient().handleMessageFromClientUI(request1);

	}

	/**
	 * Download Exam Query.Send Request To Server to download Exam
	 *
	 * @param ActivationCode the activation code of exam
	 */
	public static void DownloadExamQuery(String ActivationCode) {

		System.out.println("Called Download ExamQuery");
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			System.out.println("203 Can Not Open Connection");
			e.printStackTrace();
		}
		Msg request1 = new Msg(ActivationCode, "203");
		GuiControlBeta.getClient().handleMessageFromClientUI(request1);
	}

	/**
	 * Gets the exam manual.Called as result of "DownloadExamQuery" Method call.
	 * Receive the Message from server and Generate Word File representing Exam from It.
	 *
	 * @param msg the Message from server
	 */
	public static void GetExamManual(Object msg) {

		System.out.println("Get Exam Manual Recieved ");

		FileDialog fileDialog = new FileDialog(new Frame(), "Save",
				FileDialog.SAVE);

		fileDialog.setFilenameFilter(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.endsWith(".doc");
			}
		});
		fileDialog.setFile("Exam");
		fileDialog.setVisible(true);
		if (fileDialog.getFile() == null)
			return; // user clicked cancel in filedialog window

		// System.out.println("FileName: " + fileDialog.getFile());
		// System.out.println("FilePath: " + fileDialog.getDirectory());
		Exam Manualex = (Exam) ((Msg) msg).getMsg();
		Document doc = new Document();
		ArrayList<Question> Qst = Manualex.getQstManualExam();

		try {
			RtfWriter2.getInstance(
					doc,
					new FileOutputStream(fileDialog.getDirectory()
							+ fileDialog.getFile() + ".doc"));
			doc.open();

			Paragraph p1 = new Paragraph("Exam id : " + Manualex.getExamId());
			Paragraph p2 = new Paragraph("Course :" + Manualex.getCourseName());
			// Paragraph p3 = new
			// Paragraph("Date of Exam:"+Manualex.getCourseName());
			doc.add(p1);
			doc.add(p2);

			for (int i = 0; i < Qst.size(); i++) {
				Question q1 = Qst.get(i);
				ArrayList<String> ans = q1.getAnswer();
				ArrayList<String> pts = Manualex.getQuestionPoints();
				Paragraph p31 = new Paragraph("");
				doc.add(p31);
				Paragraph p3 = new Paragraph("Question number: "
						+ String.valueOf(i + 1));
				Chunk chunk = new Chunk("     Value of Question = "
						+ pts.get(i) + " Points");
				p3.add(chunk);
				doc.add(p3);
				Paragraph p4 = new Paragraph("Question : " + q1.getQuestion());
				doc.add(p4);
				Paragraph p5 = new Paragraph("Description "
						+ q1.getDescription());
				doc.add(p5);
				Paragraph p6 = new Paragraph(
						"Choose 1 answer from following : ");
				doc.add(p6);
				for (int j = 0; j < ans.size(); j++) {
					Paragraph p7 = new Paragraph("Answer "
							+ String.valueOf(j + 1) + ":   " + ans.get(j));
					doc.add(p7);
				}
			}
			Paragraph newline = new Paragraph("");
			doc.add(newline);
			Paragraph p7 = new Paragraph("Teacher's Notes For Exam : "
					+ Manualex.getComments());
			doc.add(p7);
			doc.close();

		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (DocumentException e) {

			e.printStackTrace();
		}

		StudentMakeExamManualSubmitPane submitExam = new StudentMakeExamManualSubmitPane(StudentFrame.contentPane, Manualex.getDuration().toString(),Manualex.getExamId());
		StudentFrame.contentPane.add(submitExam,
				"StudentMakeExamManualSubmitPane");
		CardLayout cl = (CardLayout) (StudentFrame.contentPane.getLayout());
		cl.show(StudentFrame.contentPane, "StudentMakeExamManualSubmitPane");

	}

	/**
	 * View Exam Grades Request to Server.
	 */
	public static void viewExameGrade() {
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			System.out.println("205 Can Not Open Connection");
			e.printStackTrace();
		}
		String rec = new String(
				"Select FE.ExamId,FE.Date,FE.Grade from finishedexam FE where FE.Approved = 'y' and FE.Sid ="
						+ GuiControlBeta.userid);
		Msg request = new Msg(rec, "205");

		GuiControlBeta.getClient().handleMessageFromClientUI(request);
	}

	/**
	 * Student grades request.
	 *
	 * @param msg the msg
	 */
	@SuppressWarnings("unchecked")
	public static void StudentGradesRequest(Object msg) {
		setGradesvector((Vector<Vector<String>>) ((Msg) msg).getMsg());

	}

	/**
	 * Gets the Grades vector.
	 *
	 * @return the gradesvector
	 */
	public static Vector<Vector<String>> getGradesvector() {
			return gradesvector;
	}

	/**
	 * Sets the Grades Vector.
	 *
	 * @param gradesvec the new gradesvector
	 */
	public static void setGradesvector(Vector<Vector<String>> gradesvec) {
		gradesvector = gradesvec;
	}

	/**
	 * Delete activation code of specific exam request to Server.
	 *  
	 * @param examid the Examid 
	 */
	public static void DeleteActivationCode(String examid) {
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			System.out.println("206 cannot openconnection");
			e.printStackTrace();
		}
		Msg request1 = new Msg(examid, "206");
		GuiControlBeta.getClient().handleMessageFromClientUI(request1);

	}

	/**
	 * Download Automatic Exam request to server.
	 *
	 * @param ActivationCode the activation code of Exam
	 */
	public static void DownloadExamAutomaticQuery(String ActivationCode) {

		System.out.println("Called DownloadExamAutomaticQuery");
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			System.out.println("207 Can Not Open Connection");
			e.printStackTrace();
		}
		Msg request1 = new Msg(ActivationCode, "207");
		GuiControlBeta.getClient().handleMessageFromClientUI(request1);
	}

	/**
	 * Runs Automatic Exam .Called as result of "DownloadExamAutomaticQuery" Method invocation .
	 *
	 * @param msg the Message from server
	 */
	public static void RunExamAutomatic(Object msg) {
		System.out.println("Called  RunExamAutomatic");
		Exam AutoExam = (Exam) ((Msg) msg).getMsg();
		StudentMakeExamAutomated makeExamAuto = new StudentMakeExamAutomated(
				StudentFrame.contentPane, AutoExam);
		StudentFrame.contentPane.add(makeExamAuto, "StudentMakeExamAutomated");
		CardLayout cl = (CardLayout) (StudentFrame.contentPane.getLayout());
		cl.show(StudentFrame.contentPane, "StudentMakeExamAutomated");
	}

	/**
	 * Send Automatic Exam.Sends Automatic Exam to Server.
	 *
	 * @param aExam the exam
	 */
	public static void SendAutomaticExam(Exam aExam) {
		System.out.println("Called SendAutomaticExam");
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			System.out.println("208 , Can Not Open Connection");
			e.printStackTrace();
		}
		Msg request1 = new Msg(aExam, "208");
		GuiControlBeta.getClient().handleMessageFromClientUI(request1);

	}

	/**
	 * Run extend exam time. Invoked then a Admin approves Teacher's request to extend Exam Time
	 *
	 * @param msg the Message from server , contains the new time
	 */
	public static void RunExtendExamTime(Object msg) {

		try {
			StudentMakeExamAutomated.addtimefunc(((Msg) msg).toString());
		}

		catch (Exception e) {
		}

		try {
			StudentMakeExamManualSubmitPane.addtimefunc(((Msg) msg).toString());
		}

		catch (Exception e) {
		}
	}

	/**
	 * Run lock exam. Invoked then Teacher locks the Exam execution
	 *
	 * @param msg the Message from server. 
	 */
	public static void RunLockExam(Object msg) {
		System.out.println("RunLockExam");

		try {
			StudentMakeExamAutomated.lockexamfunc(((Msg) msg).toString());
		}

		catch (Exception e) {
		}

		try {
			StudentMakeExamManualSubmitPane
					.lockexamfunc(((Msg) msg).toString());
		}

		catch (Exception e) {
		}

	}

	/**
	 * Receive finished exam info request to Server.
	 *
	 * @param exameInfo 
	 */
	public static void RecieveFinishedExamInfo(ArrayList<String> exameInfo) {

		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			System.out.println("210 , Can Not Open Connection");
			e.printStackTrace();
		}
		Msg request1 = new Msg(exameInfo, "210");
		GuiControlBeta.getClient().handleMessageFromClientUI(request1);
	}

	/**
	 * Put finished exam info.
	 *
	 * @param msg the msg
	 */
	@SuppressWarnings("unchecked")
	public static void PutFinishedExamInfo(Object msg) {

		setFinishedExamInfo((Vector<Vector<String>>) ((Msg) msg).getMsg());
	}

	/**
	 * Gets the finished exam info.
	 *
	 * @return the finished exam info
	 */
	public static Vector<Vector<String>> getFinishedExamInfo() {
		return FinishedExamInfo;
	}

	/**
	 * Sets the finished exam info.
	 *
	 * @param finishedExamInfo the new finished exam info
	 */
	public static void setFinishedExamInfo(
			Vector<Vector<String>> finishedExamInfo) {
		FinishedExamInfo = finishedExamInfo;
	}

	/**
	 * Get Manual Exams list of student.Request to Server.
	 */
	public static void GetmanualExamslist() {

		System.out.println("Called GetmanualExamslist");
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			System.out.println("209 , Can Not Open Connection");
			e.printStackTrace();
		}
		String userid = new String(GuiControlBeta.userid);
		Msg request1 = new Msg(userid, "209");
		GuiControlBeta.getClient().handleMessageFromClientUI(request1);

	}

	/**
	 * Called as Result of GetmanualExamslist method ivokation.Sets the appropriate element of GUI
	 *
	 * @param msg the Message from Server Contains list of exams
	 */
	@SuppressWarnings("unchecked")
	public static void RunGetmanualExamslist(Object msg) {
		System.out.println("Called RunGetmanualExamslist");
		ArrayList<String> examstofill = new ArrayList<String>();
		examstofill = (ArrayList<String>) ((Msg) msg).getMsg();

		StudentGetManualExamCopy.fillcomboBoxExams(examstofill);

	}

	/**
	 * Download manual exam copy request to server.
	 *
	 * @param selectedItem the ExamID
	 */
	public static void downoadManualExamCopy(String selectedItem) {
		ArrayList<String> arr = new ArrayList<String>();
		arr.add(selectedItem);
		arr.add(GuiControlBeta.userid);

		System.out.println("Called downoadManualExamCopy");
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			System.out.println("211 , Can Not Open Connection");
			e.printStackTrace();
		}
		Msg request1 = new Msg(arr, "211");
		GuiControlBeta.getClient().handleMessageFromClientUI(request1);

	}

	/**
	 * Called as a result of downoadManualExamCopy method invocation. Gets Copy of Exam file from Server
	 *
	 * @param msg the reply from server.Contains Exam file.
	 * 
	 */
	public static void getDownoadManualExamCopy(Object msg) {

		FileSend outf = (FileSend) ((Msg) msg).getMsg();

		FileDialog fileDialog = new FileDialog(new Frame(), "Save",
				FileDialog.SAVE);

		fileDialog.setFilenameFilter(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.endsWith(".doc");
			}
		});
		fileDialog.setFile("YourExam");
		fileDialog.setVisible(true);
		if (fileDialog.getFile() == null)
			return; // user clicked cancel in filedialog window

		try {

			File newFile = new File(fileDialog.getDirectory()
					+ fileDialog.getFile() + ".doc");

			// byte [] mybytearray = new byte [(int)newFile.length()];

			FileOutputStream fos = new FileOutputStream(newFile);
			BufferedOutputStream bos = new BufferedOutputStream(fos);

			// outf.initArray(mybytearray.length);
			// outf.setSize(mybytearray.length);

			bos.write(outf.getMybytearray(), 0, outf.getSize());

		}

		catch (IOException e) {

			e.printStackTrace();
		}

	}

}